package com.dream.wukong.configcenter.client.remote.http;

import com.dream.wukong.configcenter.client.core.IConnectServer;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

/**
* 描  述: rest 风格链接工具类
* 创建时间: 2018/5/23
*/
public class HttpServer implements IConnectServer {

    private static Logger logger = Logger.getLogger(HttpServer.class);
    private static HttpServer instance = null;

    public static HttpServer getInstance() {
        if (instance == null) {
            instance = new HttpServer();
        }
        return instance;
    }

    public String getServerResource(String serverUrl, String param) {
        String result = "";
        BufferedReader in = null;
        URL realUrl;
        try {
            String urlNameString = serverUrl + "?" + param;
            realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            connection.connect();

            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result = result + line;
            }
        }  catch (Exception e) {
            logger.warn("读取配置中心数据出现异常！异常信息：" + e.getLocalizedMessage(), e);
            return null;
        } finally {
            try {
                if (in != null)
                    in.close();
            } catch (Exception e) {
                logger.warn("读取配置中心关闭数据流失败，异常信息：" + e.getLocalizedMessage(), e);
            }
        }
        return result;
    }
}
